<template>
    <el-dialog v-model="dialogVisible" :title="winTitle" :close-on-click-modal="false" append-to-body width="800"
        class="editDialog" align-center>
        <el-form inline class="basicForm" label-position="right" :model="formData" ref="formRef" :rules="rules"
            label-width="120px">

            <el-form-item label="测组名称" style="width: 98%;" prop="projectName" required>
                <el-input v-model="formData.projectName"></el-input>
            </el-form-item>

            <el-form-item label="选择图片" style="width: 98%;">
                <div class="pic-box" v-for="item in selectCadArr" :key="item.id">
                    <img :src="item.fileUrl" />

                    <el-icon class="del" @click="handleFileRemove(item)">
                        <Delete />
                    </el-icon>
                    <span> {{ item.fileName }} </span>
                </div>

                <el-button plain style="width: 100%;margin-top: 5px;" @click="handleSelectAttach">选择文件</el-button>
            </el-form-item>

            <el-form-item label="备注" style="width: 98%;" prop="remark">
                <el-input v-model="formData.remark" type="textarea"></el-input>
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="dialogVisible = false" auto-insert-space>取消</el-button>
            <el-button type="primary" @click="onConfirm" auto-insert-space>确定</el-button>
        </template>


    </el-dialog>


    <select-attach ref="selectAttachRef" @confirm="handleFileChange" />
</template>


<script setup lang="js">

import { ref, defineProps, reactive } from "vue";

import { ElMessage } from "element-plus";
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { fa, fi, id } from "element-plus/es/locales.mjs";

import { projectSave } from "@/utils/requests";

import SelectAttach from "./selectAttach.vue";

let dialogVisible = ref(false);

const emits = defineEmits(["confirm"]);

let winTitle = ref("");

// 规则：trigger 千万别省
const rules = reactive({
    objName: [
        { required: true, message: '请输入测组名称', trigger: 'blur' }   // trigger 必写
    ]
})

let formRef = ref();

/* 1. 初始值常量 */
const initialForm = () => ({
    id: null,
    parentId: null,
    projectName: "",
    file: null,
    remark: "",
    attachs: []
})


let formData = reactive(initialForm());

const selectCadArr = ref([]);

const handleFileChange = (file) => {
    let cad = selectCadArr.value.find(item => item.id === file.id);

    if (!cad) {
        selectCadArr.value.push(file);

        formData.attachs.push({ attachId: file.id, name: file.fileName })
    }
}

const handleFileRemove = (file) => {
    selectCadArr.value.splice(selectCadArr.value.findIndex(item => item.id === file.id), 1);
    formData.attachs.splice(formData.attachs.findIndex(item => item.attachId == file.id), 1);
}


let isEdit = ref(false);

const openDialog = (node) => {
    dialogVisible.value = true;

    if (node.level === 1) {
        winTitle.value = "新增测组";

        Object.keys(formData).forEach(k => delete formData[k]);

        Object.assign(formData, initialForm());

        formData.parentId = node.data.id;

        isEdit.value = false;
    } else {
        winTitle.value = "编辑测组";

        Object.assign(formData, node.data);

        if (node.data.ext?.attachs) {
            node.data.ext?.attachs.forEach(file => {
                if (item.img) {

                    formData.attachs.push({ attachId: file.id, name: file.fileName })

                    selectCadArr.value.push({ id: file.id, fileUrl: file.img, fileName: file.name })
                }
            });

        }

        isEdit.value = true;
    }
};


const onConfirm = () => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            const fd = new FormData()

            if (formData.id) { fd.append('id', formData.id) }
            fd.append("parentId", formData.parentId)
            fd.append('projectName', formData.projectName)
            if (formData.remark) { fd.append('remark', formData.remark) }
            if (formData.attachs) {
                fd.append('relJson', JSON.stringify({ attachs: formData.attachs }))
            }

            projectSave(fd).then((data) => {
                if (data) {
                    emits("confirm");
                    ElMessage.success("保存成功");
                    dialogVisible.value = false;
                } else {
                    ElMessage.error("保存失败");
                }
            });
        } else {
            const firstMsg = Object.keys(fields)
                .map(k => fields[k][0]?.message)
                .find(Boolean)

            ElMessage.error(firstMsg)

            return false;
        }
    });

};

const selectAttachRef = ref(null);

const handleSelectAttach = () => {
    selectAttachRef.value.openDialog();
};

defineExpose({ openDialog });
</script>

<style scoped lang="scss">
.basicForm,
.selectionForm {
    >* {
        width: calc(50% - 20px);
        margin-right: 20px;

        .selectInput {
            flex: 1;
        }

        :deep(.el-date-editor) {
            width: 100%;
        }
    }

    >.long {
        width: calc(100% - 20px);
        margin-right: 20px;
    }

    .sumUnit {
        .text {
            margin-right: 10px;
        }
    }
}

.pic-box {
    position: relative;
    width: 148px;
    height: 148px;
    cursor: pointer;
    margin-left: 5px;
    /* 手型 */
}

.pic-box img {
    width: 100%;
    height: 120px;
    object-fit: cover;
    display: block;
}

.pic-box span {
    text-align: center;
    display: block;
}


/* 删除按钮：默认透明 + 居中 */
.del {
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 24px;
    color: #fff;
    background: rgba(0, 0, 0, .5);
    border-radius: 50%;
    padding: 6px;
    opacity: 0;
    transition: opacity .2s;
    pointer-events: none;
    /* 避免挡住 img 拖拽 */
}

/* 鼠标移入整个卡片时显示按钮 */
.pic-box:hover .del {
    opacity: 1;
    pointer-events: auto;
}
</style>